package com.example.brightness
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.EventChannel.EventSink
import io.flutter.plugin.common.EventChannel.StreamHandler
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import android.os.Handler

class BrightnessPlugin : FlutterPlugin, MethodCallHandler, StreamHandler, SensorEventListener {
  private lateinit var channel: MethodChannel
  private lateinit var eventChannel: EventChannel
  private lateinit var applicationContext: Context
  private lateinit var sensorManager: SensorManager
  private var lightSensor: Sensor? = null
  private var eventSink: EventSink? = null
  private var isListening = false

  private var lightIntensity: Float = 0.0f
  private val handler = Handler()
  override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    applicationContext = binding.applicationContext
    channel = MethodChannel(binding.binaryMessenger, "brightness")
    channel.setMethodCallHandler(this)
    eventChannel = EventChannel(binding.binaryMessenger, "brightness_event")
    eventChannel.setStreamHandler(this)
    sensorManager = applicationContext.getSystemService(Context.SENSOR_SERVICE) as SensorManager
    lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT)
    lightSensor?.let {
      sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_NORMAL)
    }
  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
    eventChannel.setStreamHandler(null)
    sensorManager.unregisterListener(this)
  }

  override fun onMethodCall(call: MethodCall, result: Result) {
    when (call.method) {
      "startBrightnessStream" -> {
        startBrightnessStream()
        result.success(null)
      }
      "stopBrightnessStream" -> {
        stopBrightnessStream()
        result.success(null)
      }
      else -> {
        result.notImplemented()
      }
    }
  }

  override fun onListen(arguments: Any?, eventSink: EventSink?) {
    this.eventSink = eventSink
  }

  override fun onCancel(arguments: Any?) {
    stopBrightnessStream()
    eventSink = null
  }

  override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
    // Not needed for light sensor
  }

  override fun onSensorChanged(event: SensorEvent?) {
    event?.let {
      if (it.sensor.type == Sensor.TYPE_LIGHT) {
        lightIntensity = it.values[0]
        if(isListening){
          eventSink?.success(lightIntensity)
        }
      }
    }
  }

  private val runnable: Runnable = object : Runnable {
    override fun run() {
      if (isListening) {
        eventSink?.success(lightIntensity)
      }
      handler.postDelayed(this, 1000) // 每隔半秒执行一次
    }
  }
  private fun startBrightnessStream() {
    if (!isListening) {
      isListening = true
      handler.postDelayed(runnable, 500)
    }
  }

  private fun stopBrightnessStream() {
    if (isListening) {
      isListening = false
      handler.removeCallbacks(runnable)
    }
  }
}
